package de.barny.main;

import javafx.event.EventHandler;
import javafx.scene.Cursor;
import javafx.scene.input.MouseEvent;
import javafx.scene.shape.Line;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.RectangleBuilder;

public class DraggableBar {

	int sensitivity = 5;
	int startWidth = 10;
	int height = 20;
	int dockSensitivity = 50;

	int hourCount;
	int[] dockingPoints;
	Boolean draggable = false;
	Rectangle bar;

	public DraggableBar(int hC) {
		bar = RectangleBuilder.create().x(0).y(0).width(startWidth)
				.height(height).build();
		bar.setId("draggableBar");

		hourCount = hC;
		dockingPoints = new int[hourCount];
		setListeners();
	}

	private void setListeners() {
		bar.setOnMouseDragged(new EventHandler<MouseEvent>() {

			@Override
			public void handle(MouseEvent evt) {
				if (draggable == true && evt.getX() > startWidth) {
					for (int i = 0; i < hourCount; i++) {
						if (evt.getX() < dockingPoints[i] - dockSensitivity
								|| evt.getX() > dockingPoints[i] + dockSensitivity) {
							bar.setWidth(evt.getX() - 10); // -10 = Cursorbreite
						} else if (evt.getX() >= dockingPoints[i] - dockSensitivity && evt.getX() <= dockingPoints[i] + dockSensitivity) {
							bar.setWidth(dockingPoints[i]);
							break;
						}
					}
				} else if (evt.getX() <= startWidth) {
					bar.setWidth(startWidth);
				}
			}
		});

		bar.setOnMouseMoved(new EventHandler<MouseEvent>() {

			@Override
			public void handle(MouseEvent evt) {
				if (evt.getX() >= (bar.getWidth() - sensitivity)
						&& evt.getX() <= (bar.getWidth())) {
					bar.setCursor(Cursor.H_RESIZE);
					draggable = true;
				} else {
					bar.setCursor(Cursor.DEFAULT);
					draggable = false;
				}
			}
		});

		bar.setOnMouseExited(new EventHandler<MouseEvent>() {

			@Override
			public void handle(MouseEvent evt) {
				bar.setCursor(Cursor.DEFAULT);
			}
		});
	}

	private void setDockingPoints(Line[] hL) {
		for (int i = 0; i < hourCount; i++) {
			dockingPoints[i] = (int) hL[i].getStartX();
			System.out.println(dockingPoints[i]);
		}
		dockingPoints[0] = 20000;
	}

	public Rectangle getBar() {
		return bar;
	}
	
	public void setHourLines(Line[] hL) {
		setDockingPoints(hL);
	}

}
